package com.pt.iwebshop.web;


import com.pt.iwebshop.model.EbUser;
import com.pt.iwebshop.service.EbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	EbUserService ebUserService;

	//1.去登录
	@RequestMapping("/to_login")
	public String toLogin(HttpSession session){

		return "login";
	}
	//1.1 登录
	@RequestMapping("/login")
	public String login(HttpSession session, EbUser ebUser){
		System.out.println("=====进入login方法==== ebUser:"+ebUser);
		//1.调用service层 查询用户是否存在
		EbUser lgnUser = ebUserService.login(ebUser);
		//2.判断使用是否存在该用户
		if(lgnUser==null){
			//携带错误信息带到首页
			session.setAttribute("msg","用户名或者密码错误，请重新登录");
			return "redirect:/login/to_login";

		}
		//登录成功则 去掉错误提示信息
		session.removeAttribute("msg");

		//3.将用户信息（用户名）传到首页 显示 欢迎 xxx ....
		session.setAttribute("lgnUserName",lgnUser.getEuUserName());

		//登录成功跳转首页  重定向
		return "redirect:/front/index";//templates/index.html
	}



	//2.去注册
	@RequestMapping("/to_register")
	public String toRegister(){
		return "register";
	}
	//2.2. 注册
	@RequestMapping("/register")
	public String register(HttpSession session, EbUser ebUser){
		System.out.println("=====进入register方法====EbUser:"+ebUser);
		//1.调用service进行注册
		//必须设置默认的用户状态 ，默认都是普通用户
		ebUser.setEuStatus(1);
		EbUser lgnUser = ebUserService.register(ebUser);
		//2.自动登录
		if(lgnUser!=null){
			session.setAttribute("lgnUserName",ebUser.getEuUserName());
			return "reg-result";
		}else{
			//TODO 注册失败 参考 登录失败 自行完成
			return null;
		}

	}

	//3.退出
	@RequestMapping("/logout")
	public String logout(HttpSession session){
		//1.清除session的用户信息
		session.removeAttribute("lgnUserName");
		return "redirect:/front/index";
	}

}